import React, { useState, useEffect, createContext } from 'react';
import {
  Tabs,
  Form,
  InputNumber,
  DatePicker,
  Select,
  Button,
  Input,
  Space,
  Message,
  Grid,
  Notification,
} from '@arco-design/web-react';
import type { DatePickerProps } from '@arco-design/web-react/es/DatePicker/interface';
import dayjs from 'dayjs'; // Keep the dayjs import
import type { Dayjs } from 'dayjs'; // Import Dayjs type directly if possible
import { storage } from '#imports';
import { browser } from 'wxt/browser'; // Import browser API
import { cozeApiClient } from '../api/coze-api'; // Import the Coze API client
import { RoleType } from '@coze/api';  // 添加 RoleType 导入
import type { SDKMessageInput } from '../api/coze-api';  // 添加 SDKMessageInput 类型导入
import './style.css';
import { mockCookies } from './cookie';
const TabPane = Tabs.TabPane;
const FormItem = Form.Item;
const { RangePicker } = DatePicker;
const { Row, Col } = Grid;

// Helper type for RangeValue - Use Dayjs from direct import
type RangeValue = [Date, Date] | null;
type NoUndefinedRangeValueType<T> = [T, T] | null;

export const FEISHU_SETTINGS_KEY = 'local:feishuSettings'; // Define a key for storage
function stringToUrl(input: string) {
  // Start with treating the provided value as a URL
  try {
    return new URL(input);
  } catch {
    // ignore
  }
  // If that fails, try assuming the provided input is an HTTP host
  try {
    return new URL('http://' + input);
  } catch {
    // ignore
  }
  // If that fails ¯\_(ツ)_/¯
  return null;
}

// --- URL Validation Patterns ---
const SINGLE_NOTE_URL_PATTERN = /^https:\/\/www\.xiaohongshu\.com\/explore\/\w+/;
const BATCH_COLLECT_URL_PATTERN = /https:\/\/www\.xiaohongshu\.com\/user\/profile\//;
// https://www.xiaohongshu.com/search_result?keyword=%25E7%259B%25B4%25E6%2592%25AD
const SEARCH_URL_PATTERN = /https:\/\/www\.xiaohongshu\.com\/search_result\?keyword=/;
// Allows /user/profile/*, /search/*, /discovery, /discovery?params

// Function to get current tab URL
async function getCurrentTabUrl(): Promise<string | undefined> {
  try {

    const tabs = await browser.tabs.query({ active: true, currentWindow: true });
    return tabs[0]?.url || '';
  } catch (error) {
    console.error("Error getting current tab URL:", error);
    return undefined;
  }
}
// 主页链接https://www.xiaohongshu.com/user/profile/5cdbe6ed000000000503a486
// 单笔记链接https://www.xiaohongshu.com/explore/645600000000000001020000

const getTabType = (url: string) => {

  if (url.indexOf('/user/profile/') !== -1) {
    return 'poster';
  }
  if (url.indexOf('/explore/') !== -1) {
    return 'note';
  }
  if (url.indexOf('/search/') > -1) {
    return 'search';
  }
  return 'unknown';
}
const getSearchWord = (url: string) => {
  const urlObj = new URL(url);
  const searchParams = new URLSearchParams(urlObj.search);
  const keyword = searchParams.get('keyword');

  return decodeURIComponent(keyword || '');

}

function App() {
  // Call useMessage hook
  const [collectForm] = Form.useForm();
  const [feishuForm] = Form.useForm();
  const [isLoading, setIsLoading] = useState(false);



  // const [message, contextHolder] = Message.useMessage();


  // Keep state for dynamic date disabling if needed
  const [dates, setDates] = useState<RangeValue>(null);
  const [isCozeClientInitialized, setIsCozeClientInitialized] = useState(false);

  // 当URL发生变化的时候获取cookie
  useEffect(() => {
    getCookies();
  }, []);

  const getCookies = async () => {
    const cks = await browser.cookies.getAll({ domain: '.xiaohongshu.com' });
    console.log('cookies', cks);
    feishuForm.setFieldsValue({
      cookie: cks.map(ck => `${ck.name}=${ck.value}`).join(';')
    });
  }

  // Load Feishu settings on component mount
  useEffect(() => {
    const loadAllSettingsAndInitialize = async () => {
      // const allSettings = await storage.getItem<any>(FEISHU_SETTINGS_KEY);
      // if (allSettings) {
      //   console.log('加载的统一设置:', allSettings);
      //   feishuForm.setFieldsValue(allSettings);
      //   if (allSettings.cozeApiToken && allSettings.cozeBotId) {
      //     try {
      //       await cozeApiClient.initialize();
      //       setIsCozeClientInitialized(true);
      //       console.log('Coze API client initialized after loading settings.');
      //     } catch (initError) {
      //       console.error("Coze API client initialization failed:", initError);
      //       Message.error('Coze API客户端初始化失败，请检查设置。');
      //     }
      //   } else {
      //     console.warn('Popup: Coze API Token or Bot ID missing in stored settings.');
      //     Message.warning('Coze API Token 或 Bot ID 未配置，部分功能可能无法使用。');
      //   }
      // } else {
      //   console.log('未找到已保存的设置。');
      // }
    };
    loadAllSettingsAndInitialize();
  }, [feishuForm]);





  const handleBatchCollect = async () => {
 

    const currentUrl = await getCurrentTabUrl();

    if (!currentUrl) {
      return;
    }
    console.log('Current Tab URL:', currentUrl);
    const tabType = getTabType(currentUrl);
    const searchWord = getSearchWord(currentUrl);
    console.log('tabType', tabType);
    console.log('searchWord', searchWord);

    const collectParams = collectForm.getFieldsValue();
    const feishuSettings = feishuForm.getFieldsValue();

    // let cozeQuery =
    //   ` 1. 小红书链接: ${currentUrl}
    //     2. 小红书的cookie: ${feishuSettings.cookie}
    //     3. 飞书多维表格token: ${feishuSettings.feishuTableAppToken}
    //     4. 链接类型: ${tabType}
    //     5. 搜索排序: ${collectParams.sort}
    //     6. 搜索关键词: ${searchWord}
    //     7. 搜索数量: ${collectParams.maxCollectCount}
    //     8. 搜索笔记类型: ${collectParams.noteType}`;
    // // 去掉回车
    // cozeQuery = cozeQuery.replace(/\n/g, '');
    const params = {
      url: currentUrl, // 小红书链接，必填项
      cookieStr: feishuSettings.cookie, // 小红书的cookie，必填项
      feishuToken: feishuSettings.feishuTableAppToken, // 飞书多维表格token，必填项
      type: tabType, // 链接类型，必填项
      sort: collectParams.sort, // 搜索排序，选填项
      keywords: searchWord, // 搜索关键词，选填项
      totalNumber: collectParams.maxCollectCount, // 搜索数量，选填项
      noteType: collectParams.noteType // 搜索笔记类型，选填项
    };

    console.log('Sending to Coze:', params);
    setIsLoading(true);

    try {


      // 使用 chatWorkflowStream 方法
      const result = await cozeApiClient.runWorkflow({
        workflowId: '7501952916490076223',
        parameters: params,                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    
        botId: feishuSettings.cozeBotId
      });
      console.log(result,'result')

      if (result.code === 0 && result.data) {
        try {
          const parsedData = JSON.parse(result.data);
          if (parsedData.output) {
            if (parsedData.output.includes('Authorize sharing your data')) {
              const authLinkMatch = parsedData.output.match(/\[here\]\((.*?)\)/);
              if (authLinkMatch?.[1]) {
                Notification.info({
                  title: '飞书表格未授权',
                  content: <a href={authLinkMatch[1]} target='_blank'>{'点击授权'}</a>,
                });
              }
            } else {
              Notification.success({
                title: '执行成功',
                content: parsedData.output
              });
            }
          }
        } catch (e) {
          Notification.error({
            title: '解析失败',
            content: '无法解析工作流返回的数据'
          });
        }
      } else {
        Notification.error({
          title: '执行失败',
          content: result.msg || '未知错误'
        });
      }

      setIsLoading(false);
      
      // 如果收集到了完整响应，显示成功通知
     
      
    } catch (error) {
      setIsLoading(false);
      console.error('Error calling Coze Workflow:', error);
      Notification.error({
        title: '操作失败',
        content: error instanceof Error ? error.message : '调用 Coze Workflow 时发生错误',
      });
    }
  };

  const handleSaveToLocal = () => {
    console.log('储存至本地', collectForm.getFieldsValue());
  };

  const handleUploadToFeishu = () => {
    console.log('上传至飞书', collectForm.getFieldsValue());
    console.log('Feishu & Coze Settings:', feishuForm.getFieldsValue());
  };

  const handleSaveFeishuSettings = async () => {
    try {
      const values = await feishuForm.validate();
      await storage.setItem(FEISHU_SETTINGS_KEY, JSON.stringify(values));
      // Message.success('设置已保存!');
      console.log('保存的设置 (飞书及Coze):', values);
      if (values.cozeApiToken && values.cozeBotId) {
        setIsCozeClientInitialized(false);
        await cozeApiClient.initialize();
        setIsCozeClientInitialized(true);
        // Message.info('Coze API 客户端已使用新设置重新初始化。');
      } else {
        setIsCozeClientInitialized(false);
        // Message.warning('Coze API Token 或 Bot ID 未配置。');
      }
    } catch (errorInfo) {
      console.log('保存设置失败:', errorInfo);
      // Message.error('请检查表单输入!');
    }
  };



  const formXhs = () => {
    return (
      <TabPane key="1" title="笔记采集">
        <Form
          form={collectForm}
          layout="vertical"
          initialValues={{
            likeThreshold: 100,
            maxCollectCount: 10,
            collectMode: 'overwrite',
            publishDateRange: null,
            noteType: '0',
            sort: '2',
          }}
        >
          {/* 排序类型排序（默认为综合，0=综合，1=最新，2=最热） */}
          <FormItem label="排序类型" field="sort">
            <Select>
              <Select.Option value="0">综合</Select.Option>
              <Select.Option value="1">最新</Select.Option>
              <Select.Option value="2">最热</Select.Option>
            </Select>
          </FormItem>
          {/* 笔记类型integer·查询类型（0=全部，1=视频，2=图文）  */}
          <FormItem label="笔记类型" field="noteType">
            <Select>
              <Select.Option value="0">全部</Select.Option>
              <Select.Option value="1">视频</Select.Option>
              <Select.Option value="2">图文</Select.Option>
            </Select>
          </FormItem>
          <FormItem label="笔记最大采集数量" field="maxCollectCount">
            <InputNumber min={1} max={999999} />
          </FormItem>

          <FormItem label="采集模式" field="collectMode">
            <Select>
              <Select.Option value="overwrite">覆盖模式 (清空之前的结果)</Select.Option>
              <Select.Option value="append">新增模式 (在之前采集的内容下面新增内容)</Select.Option>
            </Select>
          </FormItem>
          <div className="form-buttons-container">
            <Space direction="vertical" size="medium">
              <Row gutter={16}>
                <Col span={12}>
                  <Button type="primary" onClick={handleBatchCollect} long>采集当前笔记</Button>
                </Col>
                <Col span={12}>
                  <Button type="primary" onClick={handleBatchCollect} long>批量采集</Button>
                </Col>
              </Row>
              <Row gutter={16}>
                <Col span={12}>
                  <Button type="primary" onClick={handleSaveToLocal} long>储存至本地</Button>
                </Col>
                <Col span={12}>
                  <Button type="primary" onClick={handleUploadToFeishu} long>上传至飞书</Button>
                </Col>
              </Row>
            </Space>
          </div>
        </Form>
      </TabPane>
    )
  }

  // Use form instance methods if needed, or keep state for calendar interaction


  return (
    <div >
      {/* {contextHolder} */}
      <Tabs defaultActiveTab="1">
        {formXhs()}
        <TabPane key="2" title="飞书设置">
          <Form
            form={feishuForm}
            layout="vertical"
            initialValues={{
              feishuAppId: 'cli_a1234567890',
              feishuTableAppToken: 'HeT2bVRIIaXDhssozapcqdAPnOg',
              feishuTableId: 'tblFdbcODw1eisp6&view=vewpMWuRgK',
              cozeBotId: '7502263371510038580',
              cozeApiToken: 'pat_etrT1H3f2M6t93n6wDh0OcXXaPk2QnxWlPLUvU7qEplkX8gwpN0Xp6rJ5xCW1iyZ',
              cookie: '',
            }}
          >
            {/* <FormItem label="飞书 App ID" field="feishuAppId" rules={[{ required: true }]}>
              <Input  placeholder="请输入飞书 App ID" />
            </FormItem>
            <FormItem label="飞书 App Secret" field="feishuAppSecret" rules={[{ required: true }]}>
              <Input  placeholder="请输入飞书 App Secret" />
            </FormItem> */}
            <FormItem label="多维表格Token" field="feishuTableAppToken" rules={[{ required: true }]}>
              <Input placeholder="请输入多维表格 App Token" />
            </FormItem>
            <FormItem label="多维表格 Table ID" field="feishuTableId" rules={[{ required: true }]}>
              <Input placeholder="请输入多维表格 Table ID" />
            </FormItem>
            <FormItem label="Coze Bot ID" field="cozeBotId" rules={[{ required: true }]}>
              <Input placeholder="请输入Coze Bot ID" />
            </FormItem>
            <FormItem label="小红书Cookie" field="cookie" rules={[{ required: true }]}>
              <Input placeholder="请输入小红书Cookie" addAfter={<Button type="primary" onClick={getCookies} long>获取Cookie</Button>} />

            </FormItem>
            <FormItem label="Coze API Token" field="cozeApiToken" rules={[{ required: true }]}>
              <Input placeholder="请输入Coze API Token" />
            </FormItem>
            <div className="form-buttons-container">
              <Button type="primary" onClick={handleSaveFeishuSettings} long>
                保存设置
              </Button>
            </div>
          </Form>
        </TabPane>
      </Tabs>
    </div>
  );
}

export default App; 


"Authorize sharing your data with the selected AI model in Coze. Click [here](https://open.feishu.cn/open-apis/authen/v1/index?redirect_uri=https%3A%2F%2Fbot-open-api.oceancloudapi.com%2Fapi%2Foauth%2Fauthorization_code&app_id=cli_a5d6e52ba83c100c&state=22gRs4NQv0Ck4Hydv2hWsjFYMK7qNZYBJp29hRW1NPpzvnWMZDISe5ff25Ns0Pn3JteNVOsCcvKelSwLtjwM02wb2MeB247aV67-AK5clCM04CZ4NKuUoL0dmNjOMft8kKAHcXtV0t76IXn7p9trkO7S4mSVNkFbdNktrm7eO2VWkdpFEYlV3qJZy9KfC1mio4l6DXtgJC6q9Xdlxp03sw).send /cancel_oauth to cancel all oauth authorizations."
